package xyz.robinbingo.rbtask.service.impl.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.robinbingo.rbtask.bean.po.base.BasePo;
import xyz.robinbingo.rbtask.common.exception.CustomException;
import xyz.robinbingo.rbtask.mapper.base.CustomBaseMapper;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

/**
 * CustomBaseServiceImpl
 *
 * @author Robin
 * @date 2021/7/17 19:19
 **/
@Slf4j
@Service
public abstract class CustomBaseServiceImpl<M extends CustomBaseMapper<T>, T extends BasePo> extends ServiceImpl<M, T> implements IService<T> {

    @Override
    public boolean removeById(Serializable id) {
        T t = instance();
        t.setId((Long) id);
        return SqlHelper.retBool(getBaseMapper().deleteByIdWithFill(t));
    }

    @Override
    public boolean removeByMap(Map<String, Object> columnMap) {
        throw new UnsupportedOperationException("暂不支持该方法删除");
    }

    @Override
    public boolean remove(Wrapper<T> wrapper) {
        return SqlHelper.retBool(getBaseMapper().deleteByWrapperWithFill(instance(), wrapper));
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if (CollUtil.isEmpty(idList)) {
            return false;
        }
        return SqlHelper.retBool(getBaseMapper().deleteByIdsWithFill(instance(), idList));
    }

    /**
     * 获取T对应的实体
     *
     * @return T
     * @author Robin
     * @date 2021/7/19 9:57
     **/
    private T instance() {
        try {
            return classByT().getConstructor().newInstance();
        } catch (Exception e) {
            log.error("[CustomBaseServiceImpl.instance] error=", e);
        }
        throw CustomException.of("Po类生成失败");
    }

    /**
     * 获取泛型类
     *
     * @return Class
     * @author Robin
     * @date 2021/7/19 9:58
     **/
    @SuppressWarnings("unchecked")
    private Class<T> classByT() {
        return (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
    }
}
